package jp.ac.u_tokyo.dch.core.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/**
*
* @version 1.1
*
*/
public class ZipUtil {

	/**
	 * 引数で受け取ったZIP圧縮されたファイルを同じディレクトリに<BR>
	 * 展開し、展開後�Eルートディレクトリを返却します、E	 * @param file
	 * @return
	 * @throws ZipException
	 * @throws IOException
	 */
	public static String unzip(File file) throws ZipException, IOException {

        String fileName = file.getName();
        int exindex = fileName.lastIndexOf(".");
        String baseDirName = fileName.substring(0, exindex);
        File baseDir = new File(file.getParent(), baseDirName);
        baseDir.mkdir();

        ZipFile zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry ze = entries.nextElement();
            File outFile = new File(baseDir, ze.getName());
            if (ze.isDirectory()) {
                outFile.mkdirs();
            } else {
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                try {
                    bis = new BufferedInputStream(zipFile.getInputStream(ze));

                    if (!outFile.getParentFile().exists()) {
                       outFile.getParentFile().mkdirs();
                    }

                    bos = new BufferedOutputStream(new FileOutputStream(outFile));

                    int ava;
                    while ((ava = bis.available()) > 0) {
                        byte[] bs = new byte[ava];
                        bis.read(bs);
                        bos.write(bs);
                    }
                } catch (FileNotFoundException e) {
                    throw e;
                } catch (IOException e) {
                    throw e;
                } finally {
                    try {if (bis != null){bis.close();}} catch (IOException e) {}
                    try {if (bos != null){bos.close();}} catch (IOException e) {}
                }
            }
        }
        return baseDir.getAbsolutePath();
    }
}
